package com.ujf.drools;

import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

import com.ujf.drools.model.Ec2Cloud;
import com.ujf.drools.model.Stats;

/**
 * This is a sample class to launch a rule.
 */
public class DroolsGicom {
	Ec2Cloud ec2Cloud;
	private Properties props, props2;

	public static final void main(String[] args) {

		DroolsGicom d = new DroolsGicom();
		d.fire(40, 40);
		d.fire(90, 48);
		d.fire(90, 48);
		try {
			Thread.currentThread().sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		
		d.fire(90, 48);
		d.fire(2, 2);
		try {
			Thread.currentThread().sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		d.fire(2, 2);
	}

	public DroolsGicom() {
		this.props = new Properties();
		this.props2 = new Properties();
        URL url = ClassLoader.getSystemResource("drools.properties");
        URL url2 = ClassLoader.getSystemResource("probes.properties");
        if (url == null){
        	System.out.println("Fichier drools.properties introuvable.");
            System.out.println("properties:"+System.getProperties());
        }
        if (url2 == null){
        	System.out.println("Fichier sondes.properties introuvable.");
            System.out.println("properties:"+System.getProperties());
        }
        try {
			props.load(url.openStream());
			props2.load(url2.openStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
       int nbInstance = 0;
		for (String s : props2.getProperty("urls").split(" ")){
			nbInstance++;
		}
		System.out.println(nbInstance+" sont déja lancées.");

		this.ec2Cloud = new Ec2Cloud(nbInstance, props);
	}

	public void fire(int cpu, int ram) {
		System.out.println("--------");
		System.out.println("begin drools with cpu:"+cpu+" mem:"+ram);
		Stats stats = new Stats(props);
		stats.setCpu(cpu);
		stats.setMem(ram);
		DroolsGicom.startDrools(stats, ec2Cloud);

		System.out.println("end drools");
		System.out.println("--------");

	}

	private static void startDrools(Stats stats, Ec2Cloud ec2Cloud) {
		try {
			KnowledgeBase kbase = getKnowledgeBase();
			StatefulKnowledgeSession ksession = kbase
					.newStatefulKnowledgeSession();
			KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory
					.newFileLogger(ksession, "test");

			ksession.insert(ec2Cloud);
			ksession.insert(stats);

			ksession.fireAllRules();

			logger.close();
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	private static KnowledgeBase kbase;

	private static KnowledgeBase getKnowledgeBase() throws Exception {
		// load up the knowledge base
		if (kbase == null)
			kbase = readKnowledgeBase(); // lent
		return kbase;
	}

	private static KnowledgeBase readKnowledgeBase() throws Exception {
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();
		kbuilder.add(ResourceFactory.newClassPathResource("GICOMrules.drl"),
				ResourceType.DRL);
		KnowledgeBuilderErrors errors = kbuilder.getErrors();
		if (errors.size() > 0) {
			for (KnowledgeBuilderError error : errors) {
				System.err.println(error);
			}
			throw new IllegalArgumentException("Could not parse knowledge.");
		}
		KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
		kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
		return kbase;
	}

}
